package it.polimi.swKnights.SWIMv2.servlets.profile;

import it.polimi.swKnights.SWIMv2.ejb.exceptions.InvalidLoginPrivilegesException;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.LoginFailException;
import it.polimi.swKnights.SWIMv2.ejb.feedbacks.FeedbackHandlerRemote;
import it.polimi.swKnights.SWIMv2.ejb.friendsEngine.FriendshipManagerRemote;
import it.polimi.swKnights.SWIMv2.ejb.personalData.UserFinderRemote;
import it.polimi.swKnights.SWIMv2.general.Errors;
import it.polimi.swKnights.SWIMv2.general.WebsiteParameters;
import it.polimi.swKnights.SWIMv2.servlets.SwimServlet;

import java.io.IOException;
import java.util.Map;

import javax.ejb.EJBException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class MyProfileController
 */
public class MyProfileController extends SwimServlet
{
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		HttpSession session = request.getSession();
		String userName = (String) session.getAttribute("userName");
		String password = (String) session.getAttribute("password");
		String askedUser = request.getParameter("username");
		askedUser = (askedUser == null) ? userName : askedUser;
		String destination = "WEB-INF/users/profile-page/UserProfile.jsp";

		try
		{

			Map<String, String> profileUserAbilities = this
					.getUserAbilities(askedUser);
			request.setAttribute("abilitiesMap", profileUserAbilities);
			if (userName != null)
			{
				// a logged user is looking someone's profile
				this.processUserForRegistered(request, userName, password);
			}
			else
			{
				this.processUserForGuest(request);
			}

			FeedbackHandlerRemote fbr = this
					.lookUp(FeedbackHandlerRemote.class);
			Double avgFeed = fbr.getUserFeedbackAverage(askedUser);

			String strAvgFeed = String.format("%.2f", avgFeed);

			if (strAvgFeed.equals("null"))
				strAvgFeed = "0";

			request.setAttribute("avg_feed", strAvgFeed);

			request.getRequestDispatcher(destination)
					.forward(request, response); // 1

		}
		catch (LoginFailException e)
		{
			response.sendRedirect("./siteHome?error=" + Errors.session);
		}
		catch (InvalidLoginPrivilegesException e)
		{
			response.sendRedirect("./siteHome?error=" + Errors.notuser);
		}
		catch (EJBException e)
		{
			response.sendRedirect("./siteHome?error=" + Errors.notfound);
		}

	}

	private void processUserForRegistered(HttpServletRequest request,
			String userName, String password) throws LoginFailException,
			InvalidLoginPrivilegesException
	{

		if (userName.equals(request.getParameter("username"))
				|| request.getParameter("username") == null)
		{
			// looking his own profile
			this.processCurrentUser(request, userName, password);
		}
		else
		{
			// looking someone else's profile
			this.processMyFriend(request, userName, password);
		}
	}

	private void processUserForGuest(HttpServletRequest request)
			throws ServletException, IOException
	{
		String userToSee = request.getParameter("username");

		UserFinderRemote userUtilityBean = this.lookUp(UserFinderRemote.class);
		Map<String, String> parameters = userUtilityBean
				.getUserRefereces(userToSee);

		request.setAttribute("userMap", parameters);
		request.setAttribute("friend", true);
		// non intuitive but the meaning is that friend is true because
		// a guest can't add anyone as a friend, so saying friend true will hide
		// the friendship button
	}

	private void processMyFriend(HttpServletRequest request, String username,
			String password) throws LoginFailException,
			InvalidLoginPrivilegesException
	{

		FriendshipManagerRemote friendManager = this
				.lookUp(FriendshipManagerRemote.class);
		UserFinderRemote userUtilityBean = this.lookUp(UserFinderRemote.class);

		String friendUsername = request.getParameter("username");

		boolean friend = friendManager.isFriend(username, password,
				friendUsername);
		Map<String, String> parameters = userUtilityBean.getUserRefereces(
				username, password, friendUsername);
		boolean direct = this.getDirect(request);

		String image = WebsiteParameters.createImagePath(parameters
				.get("image"));

		request.setAttribute("friend", friend);
		request.setAttribute("userMap", parameters);
		request.setAttribute("direct", direct);
		request.setAttribute("image", image);

	}

	private void processCurrentUser(HttpServletRequest request,
			String username, String password) throws LoginFailException,
			InvalidLoginPrivilegesException
	{

		UserFinderRemote userUtilityBean = this.lookUp(UserFinderRemote.class);

		Map<String, String> reference = userUtilityBean.getUserRefereces(
				username, password, username);
		String image = WebsiteParameters
				.createImagePath(reference.get("image"));

		request.setAttribute("image", image);
		request.setAttribute("userMap", reference);
		request.setAttribute("friend", true);
	}

}
